//
//  NetworkTools.swift
//  Whiteboard
//
//  Created by point on 2018/1/4.
//  Copyright © 2018年 point. All rights reserved.
//

import UIKit
import Alamofire
import AFNetworking

// 请求枚举
enum MethodType {
    case get
    case post
    case put
    case delete
    
}

class NetworkTools {
    static let shareInstance : NetworkTools = {
        let tools = NetworkTools()
        return tools
    }()
    
    
    // MARK:- 判断有无网络
    func isNetWork() -> Bool {
        let manager = NetworkReachabilityManager(host: "www.baidu.com")
        return (manager?.isReachable)!
    }
    
    //IP
    fileprivate func getIp(finishedCallback :  @escaping (_ result : Any , _ success : Bool) -> ())  {
        Alamofire.request("https://api.ipify.org/?format=json", method: .get, parameters: nil).responseJSON { response in
            print(response)
            guard let result = response.result.value else {
                finishedCallback(response,true)
                return
            }
            finishedCallback(result,false)
        }
    }
    
    // MARK: - 上传多张图片已经参数上传
    func uploadImage(urlString : String, params : [String : String], data : Data, progressing: @escaping (_ result: CGFloat)->(), finishedCallback:  @escaping (_ result: Any, _ success : Bool) -> ()) {
        let headers = ["content-type" : "multipart/form-data"]
        
        
        let api : String = kHost+urlString+"?sign=1&type=1"
        Alamofire.upload(multipartFormData: { (MultipartFormData) in
            
            // 上传参数
            for (key, value) in params {
                let dataParams = value.data(using: String.Encoding.utf8)!
                MultipartFormData.append(dataParams, withName: "\(key)")
            }
            
            MultipartFormData.append(data, withName: "file", fileName: "file.jpg", mimeType: "image/jpeg")
            
        }, to: api, headers: headers, encodingCompletion: { (encodingResult) in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.uploadProgress { (progress) in
                    progressing(CGFloat(progress.fractionCompleted))
                }
                upload.validate()
                upload.responseJSON(completionHandler: { (response) in
                    if let result = response.result.value as? [String : Any] {
                        finishedCallback(result, true)
                    }else {
                        print("上传失败走这里了.....?")
                        finishedCallback(response.result.error ?? "错误", false)
                    }
                })
            case .failure(let error):
                finishedCallback(error, false)
            }
        })
    }
    
    
    func AFUpload(boolImage: Bool ,URLString: String, parameters: [String : Any]? = nil,data: Data, progressing: @escaping (_ result: CGFloat)->(),finishedCallback:  @escaping (_ result: Any, _ success : Bool) -> ()) {
        let manager = AFHTTPSessionManager()
        // manager.requestSerializer
        manager.requestSerializer.willChangeValue(forKey: "timeoutInterval")
        manager.requestSerializer.timeoutInterval = 300;
        manager.requestSerializer.didChangeValue(forKey: "timeoutInterval")
        
        
        manager.responseSerializer = AFJSONResponseSerializer()
        manager.responseSerializer.acceptableContentTypes = NSSet(array: ["text/html","text/plain","text/json"  ,"application/json","text/javascript"]) as? Set<String>
        manager.requestSerializer = AFHTTPRequestSerializer()
        
        //所有需要传递的参数都使用类似于下面token这种方法。
        //let tokenStr = "token=1234567"
        //let tokenData = tokenStr.data(using: .utf8)
        
        
        let api = kHost+URLString
        
        manager.post(api, parameters: parameters, constructingBodyWith: { (formData:AFMultipartFormData?) in
            
            if (boolImage) {
                formData?.appendPart(withFileData: data, name:"file", fileName:"file.jpg", mimeType: "image/jpeg")
            }else {
                formData?.appendPart(withFileData: data, name:"file", fileName:"file.mp4", mimeType: "video/quicktime")
                
            }
            
            //formData?.appendPart(withForm: tokenData!, name:"token")
        }, progress: { (progress:Progress) in
            progressing(CGFloat(progress.fractionCompleted))
        }, success: { (opeation, data) in
            finishedCallback(data ?? "",true)
        }) { (opeation, error) in
            finishedCallback(error,false)
        }
    }
    
    // MARK: - 上传多张图片已经参数上传
    func uploadImagesRequest(urlString : String, params : [String : String], data : [Data], progressing: @escaping (_ result: CGFloat)->(), finishedCallback:  @escaping (_ result: Any, _ success : Bool) -> ()){
        let headers = ["content-type" : "multipart/form-data",
                       //"Content-Type":"application/json",
            "Accept": "application/json"]
        
        
        let api : String = kHost+urlString+"?sign=1&type=1"
        Alamofire.upload(multipartFormData: { (MultipartFormData) in
            
            // 上传参数
            for (key, value) in params {
                let dataParams = value.data(using: String.Encoding.utf8)!
                MultipartFormData.append(dataParams, withName: "\(key)")
            }
            
            // 遍历图片，依次添加
            for i in 0..<data.count {
                MultipartFormData.append(data[i], withName: "file", fileName: "file.jpg", mimeType: "image/jpeg")
            }
        }, to: api, headers: headers, encodingCompletion: { (encodingResult) in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.uploadProgress { (progress) in
                    progressing(CGFloat(progress.fractionCompleted))
                }
                upload.validate()
                upload.responseJSON(completionHandler: { (response) in
                    if let result = response.result.value as? [String : Any] {
                        finishedCallback(result, true)
                    }else {
                        //print("上传失败走这里了.....?")
                        finishedCallback(response.result.error ?? "错误", false)
                    }
                })
            case .failure(let error):
                finishedCallback(error, false)
            }
        })
    }
    
    
    
    
    // MARK:- 请求网络
    func loadData(_ type : MethodType, URLString : String, parameters : [String : Any]? = nil, finishedCallback :  @escaping (_ result : Any , _ success : Bool) -> ()) -> DataRequest {
        // 1.获取类型
        var method : HTTPMethod = HTTPMethod.get
        if type == .get {
            method = HTTPMethod.get
        }
        if type == .post {
            method = HTTPMethod.post
        }
        if type == .put {
            method = HTTPMethod.put
        }
        if type == .delete {
            method = HTTPMethod.delete
        }
        
        let api = kHost+URLString
        
        let headers: HTTPHeaders = [
            "Accept": "application/json",
            "Content-Type":"application/json"
        ]
        
        //let mutableURLRequest: NSMutableURLRequest = NSMutableURLRequest(URL:URL)
        
        // 2.发送网络请求
      let  request = Alamofire.request(api, method: method, parameters: parameters, headers: headers).responseJSON { response in
            
            // 3.获取结果
            guard let result = response.result.value else {
                finishedCallback(response,true)
                return
            }
            
            // 4.将结果回调出去
            finishedCallback(result,false)
        }
        return request
    }
    
    func afLoadData(_ type : MethodType, URLString : String, parameters : [String : Any]? = nil, finishedCallback :  @escaping (_ result : Any , _ success : Bool) -> ()) {
        let manager = AFHTTPSessionManager()
        manager.responseSerializer = AFHTTPResponseSerializer()
        manager.requestSerializer =  AFJSONRequestSerializer()

        manager.responseSerializer.acceptableContentTypes = NSSet(array: ["text/html","text/plain","text/json"  ,"application/json","text/javascript"]) as? Set<String>

        manager.requestSerializer.setValue("application/json", forHTTPHeaderField: "Content-Type")
        manager.requestSerializer.setValue("application/json", forHTTPHeaderField: "Accept")

        
        let jsonbody : [String : Any] = [
            "name" : "jiajia",
            "age" : 18
        ]
              
        if type == .post {
            manager.post(URLString, parameters: parameters, progress: { (pro) in
                
            }, success: { (task, res) in
               
                //json 的可用性判断
                if !JSONSerialization.isValidJSONObject(res ?? "<#default value#>") {
                    print("不能转化")
                    return
                }
                //json 字符串转换为data
                guard let data = try? JSONSerialization.data(withJSONObject: jsonbody, options: .prettyPrinted) else { return }
                //data 转为字符串
                let jsonstr = String(data: data, encoding: .utf8)
                print("Json Str" + jsonstr!)
                
                //.allowFragment 允许json字符串最外层不是array 或 dictionary  但必须是有效的json格式
                //.mutableContainers 返回可变容器   array 或 dictionary
                
                if let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String : Any] {
                    print("jsonDic:",json)
//                    let name = json["name"]
//                    let age = json["age"]
//                    print("name:\(name),age:\(age)")
                }
                
            
                
//                if let json = try? JSONSerialization(with: res, options:.a) as! [String : Any] {
//                    print("jsonDic:",json)
//
//                }
      
                
               //  let dict = try? JSONSerialization.jsonObject(with: res, options: JSONSerialization.ReadingOptions)
                
                ///print(res!)
//                guard let resultDict = res as? [String : AnyObject] else {
//                  return
//                }
                
               // print("zzzzwwwwaaa",res as? [String : AnyObject] );
            }, failure: { (task, error) in
                 // print("zzzzwwwwbbb",error);
            })
        }
    }
}
